// ignore_for_file: library_private_types_in_public_api

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:kmxy_base/media_select/media_select_view.dart';
import 'package:kmxy_base/media_select/video_view.dart';
import 'package:kmxy_base/util/file_util.dart';
import 'package:kmxy_base/util/mic_util.dart';
import 'package:loading_animation_widget/loading_animation_widget.dart';
import 'package:photo_view/photo_view.dart';

import 'media_type.dart';

class CatImgVideoPageView extends StatefulWidget {
  // 数据
  final List dataList;
  // 数据索引
  final int index;
  final MediaUrlMakeFun mediaUrlMakeFun;

  const CatImgVideoPageView({
    required this.dataList,
    required this.index,
    required this.mediaUrlMakeFun,
    Key? key,
  }) : super(key: key);

  @override
  _CatImgVideoPageViewState createState() => _CatImgVideoPageViewState();
}

class _CatImgVideoPageViewState extends State<CatImgVideoPageView> {
  late PageController pageController;

  int virtualIndex = 0;

  @override
  void initState() {
    super.initState();
    virtualIndex = widget.index;
    pageController = PageController(initialPage: widget.index);
    onPageChanged(virtualIndex);
  }

  @override
  void dispose() async {
    if (MicUtil.player.playing) {
      await MicUtil.stopSound(() {});
    }
    super.dispose();
  }

  onPageChanged(int index) async {
    virtualIndex = index;
    if (mounted) {
      setState(() {});
    }
    if (MediaType.audioSuffixList.contains(
        FileUtil.getFileSuffix(widget.dataList[index]['link']).toLowerCase())) {
      if (MicUtil.player.playing) {
        await MicUtil.stopSound(() {
          if (mounted) {
            setState(() {});
          }
        });
        await MicUtil.playSound(
            widget.mediaUrlMakeFun(widget.dataList[index]['link']), () {
          if (mounted) {
            setState(() {});
          }
        }, () {
          if (mounted) {
            setState(() {});
          }
        });
      } else {
        await MicUtil.playSound(
            widget.mediaUrlMakeFun(widget.dataList[index]['link']), () {
          if (mounted) {
            setState(() {});
          }
        }, () {
          if (mounted) {
            setState(() {});
          }
        });
      }
    } else {
      if (MicUtil.player.playing) {
        await MicUtil.stopSound(() {
          if (mounted) {
            setState(() {});
          }
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(
        centerTitle: true,
        backgroundColor: Colors.black,
        foregroundColor: Colors.white,
        title: Text(
          '查看',
          style: TextStyle(
            color: Colors.white,
            fontSize: 16.sp,
            fontWeight: FontWeight.w700,
          ),
        ),
      ),
      body: Column(
        children: [
          Expanded(
            child: PageView.builder(
                controller: pageController,
                itemCount: widget.dataList.length,
                onPageChanged: onPageChanged,
                physics:
                    const PageScrollPhysics(parent: BouncingScrollPhysics()),
                itemBuilder: (BuildContext context, int index) {
                  return Padding(
                    padding: const EdgeInsets.symmetric(
                      vertical: 16,
                      horizontal: 8,
                    ),
                    child: makeView(index),
                  );
                }),
          ),
          SizedBox(height: 30, child: buildIndicator()), //滚动的小点
        ],
      ),
    );
  }

  makeView(int index) {
    if (MediaType.videoSuffixList.contains(
        FileUtil.getFileSuffix(widget.dataList[index]['link']).toLowerCase())) {
      return VideoView(
          url: widget.mediaUrlMakeFun(widget.dataList[index]['link']));
    }

    if (MediaType.imgSuffixList.contains(
        FileUtil.getFileSuffix(widget.dataList[index]['link']).toLowerCase())) {
      return InkWell(
        onTap: () {
          Navigator.pop(context);
        },
        child: PhotoView(
          imageProvider: NetworkImage(
            widget.mediaUrlMakeFun(widget.dataList[index]['link']),
          ),
        ),
      );
    }
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        SizedBox(
          width: 100.w,
          height: 100.w,
          child: InkWell(
            onTap: () async {
              if (MicUtil.player.playing) {
                await MicUtil.stopSound(() {
                  if (mounted) {
                    setState(() {});
                  }
                });
              } else {
                await MicUtil.playSound(
                    widget.mediaUrlMakeFun(widget.dataList[index]['link']), () {
                  if (mounted) {
                    setState(() {});
                  }
                }, () {
                  if (mounted) {
                    setState(() {});
                  }
                });
              }
            },
            child: MicUtil.player.playing
                ? LoadingAnimationWidget.staggeredDotsWave(
                    color: Colors.white,
                    size: 80.w,
                  )
                : Icon(
                    Icons.volume_up_rounded,
                    color: Colors.white,
                    size: 80.w,
                  ),
          ),
        ),
      ],
    );
  }

  //创建轮播图点
  Widget buildIndicator() {
    List<Widget> indicators = [];
    for (int i = 0; i < widget.dataList.length; i++) {
      indicators.add(Container(
        //当有装饰组件作为子组件的时候，是一个装饰容器
        width: 6,
        height: 6,
        margin: const EdgeInsets.symmetric(horizontal: 1.5, vertical: 10),
        decoration: BoxDecoration(
            //装饰组件，对装饰容器进行装饰用，添加颜色、图片、边框、圆角、阴影、渐变、背景混合、形状
            shape: BoxShape.circle,
            color: i == virtualIndex ? Colors.white : Colors.grey),
      ));
    }
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: indicators,
    );
  }
}
